<template>
  <div class="product-view container mx-auto py-8 bg-gray-50">
    <!-- Loading state -->
    <div
      v-if="isLoading"
      class="flex justify-center items-center min-h-[400px]"
    >
      <el-skeleton :rows="6" animated />
    </div>

    <!-- Error state -->
    <div
      v-else-if="error"
      class="flex justify-center items-center min-h-[400px]"
    >
      <el-result icon="error" :title="error" sub-title="请稍后重试">
        <template #extra>
          <el-button type="primary" @click="fetchProduct">重试</el-button>
        </template>
      </el-result>
    </div>

    <!-- Product content -->
    <template v-else-if="product">
      <!-- 1. Breadcrumbs -->
      <div class="breadcrumb mb-6 text-sm px-4">
        <el-breadcrumb separator=">">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item
            :to="{ path: '/products', query: { categoryId: product.typeId } }"
            >{{ product.gCategory }}</el-breadcrumb-item
          >
          <el-breadcrumb-item>{{ product.title }}</el-breadcrumb-item>
        </el-breadcrumb>
      </div>

      <!-- 2. Main Product Info Section -->
      <div
        class="main-content-wrapper flex flex-wrap lg:flex-nowrap gap-6 mb-8 px-4"
      >
        <!-- Left: Gallery + Share/Favorite -->
        <div class="left-gallery-section w-full lg:w-[420px] flex-shrink-0 relative">
          <!-- Product Gallery -->
          <div class="product-gallery mb-4">
            <div
              class="main-image-container border rounded overflow-hidden aspect-square bg-white flex items-center justify-center relative"
              @mouseenter="isHovering = true"
              @mouseleave="isHovering = false"
              @mousemove="handleMouseMove"
            >
              <img
                v-if="product.mainPic"
                :src="product.mainPic"
                :alt="product.title"
                class="w-full h-full object-cover"
                @error="handleImageError"
                ref="originalImage"
              />
              <el-icon v-else class="text-gray-400" :size="100"
                ><Picture
              /></el-icon>
              <!-- Hover Lens -->
              <div
                v-if="isHovering && product.mainPic"
                class="absolute border-2 border-blue-400 pointer-events-none bg-blue-50 bg-opacity-30"
                :style="lensStyle"
              ></div>
            </div>
          </div>
          
          <!-- Zoom Preview - Floating on the right -->
          <div
            v-show="isHovering && product.mainPic"
            class="zoom-preview-container absolute top-0 left-full ml-4 border-2 border-gray-300 rounded shadow-lg bg-white hidden lg:block z-50"
            style="width: 500px; height: 500px;"
          >
            <div
              class="zoom-preview"
              :style="zoomStyle"
            ></div>
          </div>
          
          <!-- 放大镜提示 -->
          <div class="text-xs text-gray-400 text-center mb-2 hidden lg:block">
            移动鼠标到图片上可放大查看细节
          </div>
          
          <!-- Share / Favorite -->
          <div
            class="text-sm text-gray-500 flex justify-center items-center gap-4"
          >
            <span class="flex items-center gap-1">
              分享:
              <el-icon
                class="cursor-pointer hover:text-red-500"
                @click="handleShare"
                ><Share
              /></el-icon>
            </span>
            <span class="text-gray-300">|</span>
            <button
              class="flex items-center hover:text-red-500"
              @click="toggleFavorite"
            >
              <el-icon class="mr-1" :class="{ 'text-red-500': isFavorited }"
                ><Star v-if="!isFavorited" /><StarFilled v-else
              /></el-icon>
              {{ isFavorited ? "取消收藏" : "收藏商品" }}
              ({{ product.sold }}+)
            </button>
          </div>
        </div>

        <!-- Middle: Product Details & Actions -->
        <div class="right-info-section flex-1">
          <div
            class="product-details-actions bg-white p-6 rounded shadow-sm h-full"
          >
            <h1 class="text-xl font-semibold mb-1">{{ product.title }}</h1>
            <p class="text-sm text-gray-500 mb-3">
              {{ product.oracleGoodsName }}
            </p>

            <!-- Price & Promotions -->
            <div class="price-section bg-gray-100 p-4 rounded mb-4">
              <div class="flex items-end mb-2 gap-2">
                <span class="text-gray-500 text-sm mr-2">价格</span>
                <!-- Seckill Price -->
                <template v-if="seckillPromotions.length > 0">
                  <span class="text-red-500 text-2xl font-bold leading-none">
                    ¥{{ Number(seckillPromotions[0].seckillPrice).toFixed(2) }}
                  </span>
                  <span class="text-gray-500 text-base line-through">
                    {{ formatPriceAuth(product.price, !!userStore.token) }}
                  </span>
                  <el-tag type="danger" size="small" effect="dark" class="ml-2">秒杀价</el-tag>
                </template>
                <!-- Regular Price -->
                <template v-else>
                  <span class="text-red-500 text-2xl font-bold leading-none">
                    {{ formatPriceAuth(product.price, !!userStore.token, userStore.userInfo?.discount, product.noDiscounts) }}
                  </span>
                  <span v-if="userStore.userInfo?.discount && product.noDiscounts !== 1" class="text-gray-500 text-base line-through">
                    {{ formatPriceAuth(product.price, !!userStore.token) }}
                  </span>
                </template>
                <!-- <div
                  class="text-gray-500 text-xs ml-auto flex flex-col items-end"
                >
                  <span>累计销量 {{ product.sold }}+</span>
                </div> -->
              </div>
              
              <!-- Promotion Tags -->
              <div v-if="hasPromotions" class="mt-3 space-y-2">
                <!-- Buy Gift Promotions -->
                <div v-for="(buyGift, index) in buyGiftPromotions" :key="`buy-gift-${index}`" class="flex items-center gap-2">
                  <el-tag type="danger" effect="dark" size="small">
                    <el-icon class="mr-1"><Present /></el-icon>
                    买{{ Number(buyGift.num) }}送{{ Number(buyGift.freeNum) }}
                  </el-tag>
                  <span class="text-xs text-gray-600">
                    赠品：{{ buyGift.freeGoodsInfo?.title || buyGift.remark || '赠品信息待更新' }}
                  </span>
                </div>
                
                <!-- Seckill Promotions -->
                <div v-for="(seckill, index) in seckillPromotions" :key="`seckill-${index}`" class="flex items-center gap-2">
                  <el-tag type="danger" effect="dark" size="small">
                    <el-icon class="mr-1"><Lightning /></el-icon>
                    限时秒杀
                  </el-tag>
                  <span class="text-sm font-bold text-red-600">¥{{ Number(seckill.seckillPrice).toFixed(2) }}</span>
                  <span class="text-xs text-gray-500">原价 ¥{{ product.price }}</span>
                  <span class="text-xs text-orange-600">仅剩{{ Math.floor(Number(seckill.seckillStorNum)) }}件</span>
                </div>
                
                <!-- Combo Promotions -->
                <div v-if="comboPromotions.length > 0" class="flex items-center gap-2">
                  <el-tag type="warning" effect="dark" size="small">
                    <el-icon class="mr-1"><Box /></el-icon>
                    套餐优惠
                  </el-tag>
                  <span class="text-xs text-gray-600">该商品参与{{ comboPromotions.length }}个套餐活动</span>
                </div>
                
                <!-- Full Reduction Info -->
                <div v-if="activePromotions.some(p => p.promType === 'MJ')" class="flex items-center gap-2">
                  <el-tag type="success" effect="dark" size="small">
                    <el-icon class="mr-1"><PriceTag /></el-icon>
                    满减活动
                  </el-tag>
                  <span class="text-xs text-gray-600">购物车满额享优惠</span>
                </div>
              </div>
            </div>

            <!-- Promotion Details Section -->
            <div v-if="hasPromotions" class="promotion-details bg-gradient-to-r from-red-50 to-orange-50 border border-red-200 rounded-lg p-4 mb-4">
              <h4 class="text-lg font-semibold text-red-600 mb-3 flex items-center">
                <el-icon class="mr-2"><Lightning /></el-icon>
                促销活动详情
              </h4>
              
              <!-- Buy Gift Details -->
              <div v-if="buyGiftPromotions.length > 0" class="mb-4">
                <h5 class="font-medium text-gray-800 mb-2">买赠活动详情</h5>
                <div v-for="(buyGift, index) in buyGiftPromotions" :key="`buy-gift-detail-${index}`" 
                     class="bg-white rounded-lg p-3 border border-red-100">
                  <div class="flex items-start gap-4">
                    <div class="flex-1">
                      <p class="font-medium text-gray-800 mb-2">
                        买{{ Number(buyGift.num) }}{{ product.unit }} 
                        <span v-if="buyGift.freeGoodsInfo && buyGift.freeGoodsInfo.id">送 {{ buyGift.freeGoodsInfo.title }} {{ Number(buyGift.freeNum) }}{{ buyGift.freeGoodsInfo?.unit || '件' }}</span>
                      </p>
                      <div class="text-sm text-gray-600 space-y-1">
                        <!-- 赠品信息 -->
                        <div v-if="buyGift.freeGoodsInfo && buyGift.freeGoodsInfo.id">
                          <p>赠品：{{ buyGift.freeGoodsInfo.title }}</p>
                          <p>赠品规格：{{ buyGift.freeGoodsInfo.goodsSpec }}</p>
                          <p class="text-red-600 font-medium">赠品价值：¥{{ Number(buyGift.freeTaxPrice).toFixed(2) }}/{{ buyGift.freeGoodsInfo.unit }}</p>
                          <!-- 赠品有效期 -->
                          <div v-if="buyGift.freeGoodsInfo.nearestExpiredDate" class="mt-1">
                            <div class="flex items-center gap-2">
                              <span class="text-xs text-gray-500">赠品有效期:</span>
                              <span class="text-xs text-orange-600 font-medium">{{ formatBatchDate(buyGift.freeGoodsInfo.nearestExpiredDate) }}</span>
                              <el-tag
                                v-if="isNearExpiry(buyGift.freeGoodsInfo.nearestExpiredDate)"
                                size="small"
                                type="danger"
                                effect="plain"
                                class="!text-xs"
                              >
                                近效期
                              </el-tag>
                            </div>
                          </div>
                        </div>
                        <!-- 无赠品时的备注信息 -->
                        <div v-else>
                          <p class="text-gray-600">{{ buyGift.remark || '赠品信息待更新' }}</p>
                        </div>
                      </div>
                    </div>
                    <div class="text-right">
                      <p class="text-sm text-gray-500">活动价</p>
                      <p class="text-xl font-bold text-red-600">¥{{ calculateDiscountedPrice(Number(buyGift.taxprice)) }}</p>
                      <p class="text-xs text-gray-500">买{{ Number(buyGift.num) }}件</p>
                      <el-button
                        type="danger"
                        size="small"
                        class="mt-2"
                        @click="handleBuyGiftPurchase"
                        :disabled="!canAddToCart || isBuyGiftPurchasing"
                        :loading="isBuyGiftPurchasing"
                      >
                        <el-icon class="mr-1"><Present /></el-icon>{{ isBuyGiftPurchasing ? '购买中...' : '参与买赠' }}
                      </el-button>
                    </div>
                  </div>
                </div>
              </div>
              
              <!-- Seckill Details -->
              <div v-if="seckillPromotions.length > 0" class="mb-4">
                <h5 class="font-medium text-gray-800 mb-2">秒杀活动详情</h5>
                <div v-for="(seckill, index) in seckillPromotions" :key="`seckill-detail-${index}`" 
                     class="bg-white rounded-lg p-3 border border-red-100">
                  <div class="flex items-start gap-4">
                    <div class="flex-1">
                      <p class="font-medium text-gray-800 mb-2">限时秒杀价</p>
                      <p class="text-2xl font-bold text-red-600">¥{{ Number(seckill.seckillPrice).toFixed(2) }}</p>
                      <p class="text-sm text-gray-500 line-through">原价 ¥{{ product.price }}</p>
                      <div class="mt-2">
                        <p class="text-sm text-orange-600 font-medium">仅剩 {{ Math.floor(Number(seckill.seckillStorNum)) }} 件</p>
                        <p class="text-xs text-gray-500">限购 {{ Math.floor(Number(seckill.seckillNum)) }} 件/单</p>
                        <div class="mt-2">
                          <div class="w-32 bg-gray-200 rounded-full h-2">
                            <div
                              class="bg-gradient-to-r from-red-500 to-orange-500 h-2 rounded-full transition-all duration-300"
                              :style="{ width: `${Math.max(10, (Math.floor(Number(seckill.seckillStorNum)) / (Math.floor(Number(seckill.seckillStorNum)) + 50)) * 100)}%` }"
                            ></div>
                          </div>
                        </div>
                      </div>
                    </div>
                    <div class="text-right">
                      <p class="text-sm text-gray-500 mb-2">秒杀数量</p>
                      <div class="flex items-center gap-2 mb-3">
                        <el-input-number
                          v-model="seckillQuantity"
                          :min="1"
                          :max="Math.min(Math.floor(Number(seckill.seckillStorNum)), Math.floor(Number(seckill.seckillNum)))"
                          size="small"
                          style="width: 100px"
                        />
                        <span class="text-xs text-gray-500">{{ product.unit }}</span>
                      </div>
                      <p class="text-xs text-gray-500 mb-3">
                        总价：¥{{ (Number(seckill.seckillPrice) * seckillQuantity).toFixed(2) }}
                      </p>
                      <el-button
                        type="danger"
                        size="small"
                        @click="handleSeckillPurchase"
                        :disabled="!canSeckill || isSeckillPurchasing"
                        :loading="isSeckillPurchasing"
                      >
                        <el-icon class="mr-1"><Lightning /></el-icon>{{ isSeckillPurchasing ? '秒杀中...' : '立即秒杀' }}
                      </el-button>
                    </div>
                  </div>
                </div>
              </div>
              
              <!-- Combo Details -->
              <div v-if="comboPromotions.length > 0" class="mb-4">
                <h5 class="font-medium text-gray-800 mb-2">套餐活动详情</h5>
                <div class="space-y-2">
                  <div v-for="(combo, index) in comboPromotions" :key="`combo-${index}`" 
                       class="bg-white rounded-lg p-3 border border-orange-100">
                    <div class="flex items-center justify-between">
                      <div>
                        <p class="font-medium text-gray-800">{{ combo.promName }}</p>
                        <p class="text-xs text-gray-500">套餐编号：{{ combo.billCode }}</p>
                        <p class="text-sm text-gray-600 mt-1">该商品参与此套餐活动，可享受组合优惠</p>
                      </div>
                      <el-button
                        type="warning"
                        size="small"
                        plain
                        @click="viewComboPromotions"
                      >
                        <el-icon class="mr-1"><Box /></el-icon>查看详情
                      </el-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- Service Promises
            <div
              class="service-promises text-xs text-gray-500 mb-4 flex items-center gap-4 flex-wrap"
            >
              <span class="text-gray-500 text-sm mr-1 shrink-0">服务</span>
              <span class="flex items-center"
                ><el-icon class="mr-1 text-red-500"><CircleCheck /></el-icon
                ><el-tag size="small" effect="plain" class="ml-1"
                  >正品保证</el-tag
                ></span
              >
              <span class="flex items-center"
                ><el-icon class="mr-1 text-red-500"><Coin /></el-icon
                ><el-tag size="small" effect="plain" class="ml-1"
                  >专业咨询</el-tag
                ></span
              >
              <span class="flex items-center"
                ><el-icon class="mr-1 text-red-500"><Van /></el-icon
                ><el-tag size="small" effect="plain" class="ml-1"
                  >品质保障</el-tag
                ></span
              >
            </div> -->

            <!-- Product Info -->
            <div class="mb-4 border-t pt-4">
              <div class="grid grid-cols-2 gap-x-8 gap-y-3">
                <!-- Left Column -->
                <div class="space-y-3">
                  <div class="flex items-center">
                    <span
                      class="text-gray-500 text-sm mr-4 w-16 shrink-0 whitespace-nowrap"
                      >商品规格</span
                    >
                    <span class="text-gray-700 text-sm">{{
                      product.goodsSpec
                    }}</span>
                    <el-tag size="small" type="info" effect="plain" class="ml-2"
                      >标准规格</el-tag
                    >
                  </div>
                  <div class="flex items-center">
                    <span
                      class="text-gray-500 text-sm mr-4 w-16 shrink-0 whitespace-nowrap"
                      >包装单位</span
                    >
                    <span class="text-gray-700 text-sm">{{
                      product.unit
                    }}</span>
                    <el-tag size="small" type="info" effect="plain" class="ml-2"
                      >标准包装</el-tag
                    >
                  </div>
                  <div class="flex items-center">
                    <span
                      class="text-gray-500 text-sm mr-4 w-16 shrink-0 whitespace-nowrap"
                      >包装类型</span
                    >
                    <div class="flex flex-col gap-1">
                      <div class="flex items-center gap-2">
                        <el-tag
                          size="small"
                          :type="'success'"
                          v-if="product.midpack > 1"
                          effect="plain"
                        >
                          中包装 {{ product.midpack }} {{ product.unit }}
                        </el-tag>
                        <el-tag
                          size="small"
                          :type="'warning'"
                          effect="plain"
                        >
                          件包装 {{ Number(product.qty) }}
                        </el-tag>
                
                      </div>
                      <div
                        v-if="product.midpack > 1"
                        class="flex items-center gap-2"
                      >
                        <el-tag
                          v-if="product.isMidpackSaleDisabled === 1"
                          size="small"
                          :type="'warning'"
                          effect="plain"
                          class="!text-xs"
                        >
                          不支持拆零
                        </el-tag>
                        <span
                          v-if="product.isMidpackSaleDisabled === 1"
                          class="text-xs text-orange-600"
                        >
                          需按{{ product.midpack }}{{ product.unit }}倍数购买
                        </span>
                      </div>
                    </div>
                  </div>
                  <div class="flex items-center">
                    <span
                      class="text-gray-500 text-sm mr-4 w-16 shrink-0 whitespace-nowrap"
                      >商品分类</span
                    >
                    <span class="text-gray-700 text-sm">{{
                      product.gCategory
                    }}</span>
                  </div>
                  <div class="flex items-center">
                    <span
                      class="text-gray-500 text-sm mr-4 w-16 shrink-0 whitespace-nowrap"
                      >商品编码</span
                    >
                    <span class="text-gray-700 text-sm">{{
                      product.goodsCode
                    }}</span>
                  </div>
                </div>

                <!-- Right Column -->
                <div class="space-y-3">
                  <div class="flex items-center">
                    <span
                      class="text-gray-500 text-sm mr-4 w-16 shrink-0 whitespace-nowrap"
                      >药品剂型</span
                    >
                    <span class="text-gray-700 text-sm">{{
                      product.formula
                    }}</span>
                  </div>
                </div>
              </div>

              <!-- Full Width Items -->
              <div class="space-y-3 mt-4">
                <div class="flex flex-col">
                  <div class="flex items-center mb-2">
                    <span
                      class="text-gray-500 text-sm mr-4 w-16 shrink-0 whitespace-nowrap"
                      >生产厂家</span
                    >
                    <span class="text-gray-700 text-sm">{{
                      product.manufacturer
                    }}</span>
                    <el-tag
                      size="small"
                      type="success"
                      effect="plain"
                      class="ml-2"
                      >正规厂家</el-tag
                    >
                  </div>
                  <div class="text-xs text-gray-400 ml-20">
                    本商品由正规厂家生产，质量有保障
                  </div>
                </div>
                <div class="flex flex-col">
                  <div class="flex items-center mb-2">
                    <span
                      class="text-gray-500 text-sm mr-4 w-16 shrink-0 whitespace-nowrap"
                      >批准文号</span
                    >
                    <span class="text-gray-700 text-sm">{{
                      product.approvalNo
                    }}</span>
                    <el-tag
                      size="small"
                      type="success"
                      effect="plain"
                      class="ml-2"
                      >国药准字</el-tag
                    >
                  </div>
                  <div class="text-xs text-gray-400 ml-20">
                    国家药品监督管理局批准文号，安全可靠
                  </div>
                </div>

                <!-- 近效期信息 -->
                <div
                  v-if="product.expiredDate"
                  class="flex items-center"
                >
                  <span
                    class="text-gray-500 text-sm mr-4 w-16 shrink-0 whitespace-nowrap"
                    >有效期</span
                  >
                  <span class="text-gray-700 text-sm">{{
                    formatBatchDate(product.expiredDate)
                  }}</span>
                </div>
              </div>

              <!-- Warm Reminder -->
              <div class="bg-blue-50 border-l-4 border-blue-400 p-3 mt-4">
                <div class="flex">
                  <div class="flex-shrink-0">
                    <el-icon class="text-blue-400"><InfoFilled /></el-icon>
                  </div>
                  <div class="ml-3">
                    <p class="text-sm text-blue-700">
                      温馨提示：请仔细核对商品规格、包装单位等信息，确保与您的需求相符。
                    </p>
                  </div>
                </div>
              </div>
            </div>

            <!-- Quantity & Actions -->
            <div
              class="quantity-actions border-t pt-4 flex items-center gap-4 flex-wrap"
            >
              <span class="text-gray-500 text-sm mr-4 w-12 shrink-0">数量</span>
              <el-input-number
                v-model="selectedQuantity"
                :min="minQuantity"
                :max="Math.max(minQuantity, parseInt(product.storNum) || 10)"
                :step="quantityStep"
                size="default"
                class="w-28"
              />
              <span class="text-xs text-gray-400">
                库存
                <span :class="getStockStatusClass(product.storNum)">{{
                  getStockStatusText(product.storNum)
                }}</span>
                <span
                  v-if="
                    product.midpack > 1 && product.isMidpackSaleDisabled === 1
                  "
                  class="text-orange-600 ml-2"
                >
                  （按{{ product.midpack }}{{ product.unit }}倍数购买）
                </span>
              </span>
              <div class="flex gap-3 ml-auto">
                <!-- 普通购买按钮 (始终显示) -->
                <el-button
                  type="danger"
                  size="large"
                  plain
                  @click="addToCart"
                  :disabled="!canAddToCart || isAddingToCart"
                  :loading="isAddingToCart"
                >
                  <el-icon class="mr-1"><ShoppingCart /></el-icon>加入购物车
                </el-button>
                
                <!-- View Combo Button -->
                <el-button
                  v-if="comboPromotions.length > 0"
                  type="warning"
                  size="large"
                  plain
                  @click="viewComboPromotions"
                >
                  <el-icon class="mr-1"><Box /></el-icon>查看套餐
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 3. Bottom Details Section (Tabs) -->
      <div
        class="bottom-layout-wrapper flex flex-wrap lg:flex-nowrap gap-6 px-4"
      >
        <div class="bottom-details flex-1 bg-white rounded shadow-sm">
          <el-tabs v-model="activeTab" class="product-detail-tabs">
            <el-tab-pane label="规格参数" name="specs">
              <div class="p-4 min-h-[300px]">
                <ul
                  class="grid grid-cols-2 md:grid-cols-3 gap-x-8 gap-y-3 text-sm text-gray-700"
                >
                  <li>
                    <span class="text-gray-500 mr-2">商品名称:</span>
                    {{ product.title }}
                  </li>
                  <li>
                    <span class="text-gray-500 mr-2">规格:</span>
                    {{ product.goodsSpec }}
                  </li>
                  <li>
                    <span class="text-gray-500 mr-2">生产厂家:</span>
                    {{ product.manufacturer }}
                  </li>
                  <li>
                    <span class="text-gray-500 mr-2">批准文号:</span>
                    {{ product.approvalNo }}
                  </li>
                  <li>
                    <span class="text-gray-500 mr-2">剂型:</span>
                    {{ product.formula }}
                  </li>
                  <li>
                    <span class="text-gray-500 mr-2">商品分类:</span>
                    {{ product.gCategory }}
                  </li>
                  <li>
                    <span class="text-gray-500 mr-2">商品编码:</span>
                    {{ product.goodsCode }}
                  </li>
            
                  <li>
                    <span class="text-gray-500 mr-2">库存数量:</span>
                    <span :class="getStockStatusClass(product.storNum)">{{
                      getStockStatusText(product.storNum)
                    }}</span>
                  </li>
                </ul>
              </div>
            </el-tab-pane>
            <el-tab-pane label="商品详情" name="details">
              <div class="p-4 min-h-[300px]">
                <div class="bg-yellow-50 border-l-4 border-yellow-400 p-4 mb-4">
                  <div class="flex">
                    <div class="flex-shrink-0">
                      <el-icon class="text-yellow-400"><Warning /></el-icon>
                    </div>
                    <div class="ml-3">
                      <p class="text-sm text-yellow-700">
                        温馨提醒：若商品与图片不完全一致，请以收到的商品实物为准。
                      </p>
                    </div>
                  </div>
                </div>
                <p class="text-gray-600">商品详情信息待完善...</p>
              </div>
            </el-tab-pane>
            <el-tab-pane
              :label="`商品评价 (${product.sold || 0})`"
              name="reviews"
            >
              <div class="p-4 min-h-[300px]">
                <p class="text-gray-600">暂无评价</p>
              </div>
            </el-tab-pane>
            <el-tab-pane label="注意事项" name="notes">
              <div class="p-4 min-h-[300px] text-sm space-y-4">
                <h5 class="font-semibold">药品品质保证</h5>
                <p class="text-gray-600">
                  本店所有药品均来自正规厂家，经过严格的质量检验，确保药品安全有效。
                </p>

                <h5 class="font-semibold">药品储存条件</h5>
                <p class="text-gray-600">
                  请按照药品说明书要求储存，避免阳光直射、高温潮湿环境，确保药品品质。
                </p>

                <h5 class="font-semibold">用药安全提示</h5>
                <p class="text-gray-600">
                  请仔细阅读药品说明书，按照医嘱或药师指导用药，如有不适请及时就医。
                </p>

                <h5 class="font-semibold">药品有效期</h5>
                <p class="text-gray-600">
                  所有药品均在有效期内，请勿使用过期药品，以确保用药安全。
                </p>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>

        <!-- Right Sidebar -->
        <div class="right-sidebar w-full lg:w-[300px] flex-shrink-0 space-y-6">
          <!-- Hot Sales -->
          <div class="hot-sales bg-white rounded shadow-sm p-4">
            <h3 class="text-lg font-semibold mb-4 flex items-center">
              <el-icon class="mr-2 text-red-500"><StarFilled /></el-icon>
              热销榜
            </h3>
            <div v-if="isLoadingHotSales" class="space-y-4">
              <div
                v-for="i in 5"
                :key="i"
                class="hot-sale-item flex items-center gap-3"
              >
                <el-skeleton :rows="0" animated class="w-16 h-16" />
                <div class="flex-1">
                  <el-skeleton :rows="2" animated />
                </div>
              </div>
            </div>
            <div v-else class="space-y-4">
              <div
                v-for="item in hotSales.slice(0, 5)"
                :key="item.id"
                class="hot-sale-item flex items-center gap-3 cursor-pointer group"
                @click="openProductInNewTab(item.id)"
              >
                <div
                  class="w-16 h-16 bg-gray-100 rounded overflow-hidden flex items-center justify-center"
                >
                  <img
                    v-if="item.mainPic"
                    :src="item.mainPic"
                    :alt="item.title"
                    class="w-full h-full object-cover"
                    @error="handleImageError"
                  />
                  <el-icon v-else class="text-gray-400" :size="30"
                    ><Picture
                  /></el-icon>
                </div>
                <div class="flex-1 min-w-0">
                  <p
                    class="text-sm text-gray-700 truncate group-hover:text-red-500"
                  >
                    {{ item.title }}
                  </p>
                  <p class="text-red-500 text-sm">
                    {{ formatPriceAuth(item.price, !!userStore.token) }}
                  </p>
                </div>
              </div>
            </div>
          </div>

          <!-- Recommended Products -->
          <!-- <div class="recommended-products bg-white rounded shadow-sm p-4">
            <h3 class="text-lg font-semibold mb-4 flex items-center">
              <el-icon class="mr-2 text-blue-500"><Star /></el-icon>
              猜你喜欢
            </h3>
            <div class="space-y-4">
              <div
                v-for="i in 5"
                :key="i"
                class="recommended-item flex items-center gap-3 cursor-pointer group"
              >
                <div
                  class="w-16 h-16 bg-gray-100 rounded flex items-center justify-center"
                >
                  <el-icon class="text-gray-400" :size="30"
                    ><Picture
                  /></el-icon>
                </div>
                <div class="flex-1 min-w-0">
                  <p
                    class="text-sm text-gray-700 truncate group-hover:text-red-500"
                  >
                    推荐商品 {{ i }}
                  </p>
                  <p class="text-red-500 text-sm">
                    ¥{{ (Math.random() * 100).toFixed(2) }}
                  </p>
                </div>
              </div>
            </div>
          </div> -->
        </div>
      </div>
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Star,
  StarFilled,
  ShoppingCart,
  Share,
  Picture,
  Warning,
  InfoFilled,
  Present,
  Lightning,
  Box,
  PriceTag,
} from "@element-plus/icons-vue";
import { useClipboard } from "@vueuse/core";
import { getGoodsInfo, getGoodsList } from "@/api/modules/goods";
import type { Goods } from "@/api/modules/goods";
import { getPromotionsByGoodsId } from "@/api/modules/promotion";
import type { 
  Promotion, 
  BuyGiftPromotion, 
  SeckillPromotion, 
  ComboPromotion,
  BuyGiftDetail,
  SeckillDetail
} from "@/api/modules/promotion";
import { promotionApi } from "@/api";
import { useCartStore } from "@/stores/cart";
import { useCollectStore } from "@/stores/collect";
import { useFootprintStore } from "@/stores/footprint";
import { getStockStatusText, getStockStatusClass } from "@/lib/stockUtils";
import { useUserStore } from "@/stores/user";
import { formatPriceAuth } from "@/lib/utils";

const route = useRoute();
const router = useRouter();
const { copy } = useClipboard();
const productId = computed(() => {
  const id = route.params.id;
  console.log("Route params:", route.params);
  return typeof id === "string" ? Number(id) : 0;
});

// Product data and loading state
const product = ref<Goods | null>(null);
const isLoading = ref(true);
const error = ref<string | null>(null);
const isFavorited = ref(false);

// Hot sales data
const hotSales = ref<Goods[]>([]);
const isLoadingHotSales = ref(false);

// Add to cart loading state
const isAddingToCart = ref(false);

// Promotion data
const activePromotions = ref<Promotion[]>([]);
const buyGiftPromotions = ref<BuyGiftDetail[]>([]);
const seckillPromotions = ref<SeckillDetail[]>([]);
const comboPromotions = ref<ComboPromotion[]>([]);
const hasPromotions = computed(() => activePromotions.value.length > 0);

const cartStore = useCartStore();
const collectStore = useCollectStore();
const footprintStore = useFootprintStore();
const userStore = useUserStore();

// 检查商品收藏状态
async function checkCollectStatus() {
  if (product.value) {
    isFavorited.value = await collectStore.checkIsCollected(product.value.id);
  }
}

// Fetch product data
async function fetchProduct() {
  const id = productId.value;
  if (!id) {
    error.value = "商品ID无效";
    ElMessage.error("商品ID无效");
    return;
  }

  try {
    isLoading.value = true;
    error.value = null;
    console.log("Fetching product with ID:", id);
    const response: any = await getGoodsInfo(id);
    if (response.code === 1000 && response.data) {
      product.value = response.data;
      
      // 获取商品促销信息
      if (product.value && product.value.goodsId) {
        console.log("Fetching promotions for goodsId:", product.value.goodsId);
        try {
          const promotionsResponse = await getPromotionsByGoodsId(product.value.goodsId);
          console.log("Promotions response:", promotionsResponse);
          if (promotionsResponse.code === 1000 && promotionsResponse.data) {
            console.log("Promotions data:", promotionsResponse.data);
            
            // 清空之前的促销数据
            activePromotions.value = [];
            buyGiftPromotions.value = [];
            seckillPromotions.value = [];
            comboPromotions.value = [];
            
            // 过滤活动中的促销
            const now = new Date();
            const validPromotions = promotionsResponse.data.filter((promo: Promotion) => {
              const startTime = new Date(promo.startTime);
              const endTime = new Date(promo.endTime);
              return promo.status === 1 && now >= startTime && now <= endTime;
            });
            
            activePromotions.value = validPromotions;
            
            // 分类处理不同类型的促销
            validPromotions.forEach((promo: any) => {
              // 处理买赠促销（支持中文和英文）
              if (promo.promType === 'MZ' || promo.promType === '买赠') {
                const buyGiftPromo = promo as BuyGiftPromotion;
                
                // 找出当前商品的买赠详情
                const buyGiftDetail = buyGiftPromo.details.find(
                  detail => detail.goodsId === product.value!.goodsId && detail.status === 1
                );
                
                if (buyGiftDetail) {
                  // 将促销活动信息附加到详情中
                  buyGiftPromotions.value.push({
                    ...buyGiftDetail,
                    promotion: buyGiftPromo
                  } as any);
                }
              }
              // 处理秒杀促销
              else if (promo.promType === 'MS' || promo.promType === '秒杀') {
                const seckillPromo = promo as SeckillPromotion;
                // 找出当前商品的秒杀详情
                const seckillDetail = seckillPromo.details.find(
                  detail => detail.goodsId === product.value!.goodsId && detail.status === 1
                );
                if (seckillDetail) {
                  // 将促销活动信息附加到详情中
                  seckillPromotions.value.push({
                    ...seckillDetail,
                    promotion: seckillPromo
                  } as any);
                }
              }
              // 处理套餐促销
              else if (promo.promType === 'TC' || promo.promType === '套餐') {
                const comboPromo = promo as ComboPromotion;
                // 检查套餐中是否包含当前商品
                const hasCurrentProduct = comboPromo.details.some(
                  detail => detail.goodsId === product.value!.goodsId && detail.status === 1
                );
                if (hasCurrentProduct) {
                  comboPromotions.value.push(comboPromo);
                }
              }
              // 处理满减促销
              else if (promo.promType === 'MJ' || promo.promType === '满减') {
                // 满减促销通常适用于所有商品，无需特殊过滤
              }
            });
          }
        } catch (promotionErr) {
          console.error("Failed to fetch promotions:", promotionErr);
        }
      }
    }
    await checkCollectStatus(); // 获取商品信息后检查收藏状态
    // 添加足迹记录
    await footprintStore.addToFootprint(id);
  } catch (err) {
    error.value = "获取商品信息失败";
    ElMessage.error("获取商品信息失败");
  } finally {
    isLoading.value = false;
  }
}

// Fetch hot sales data
async function fetchHotSales() {
  try {
    isLoadingHotSales.value = true;
    const response: any = await getGoodsList({
      order: "sold",
      sort: "desc",
      page: 1,
      size: 10,
    });
    if (response.code === 1000 && response.data) {
      hotSales.value = response.data.list;
    }
  } catch (err) {
    ElMessage.error("获取热销商品失败");
  } finally {
    isLoadingHotSales.value = false;
  }
}

// Watch for route changes
watch(
  () => route.params.id,
  (newId) => {
    console.log("Route ID changed:", newId);
    if (newId) {
      fetchProduct();
      fetchHotSales();
    }
  },
  { immediate: true }
);

const selectedQuantity = ref(1);
const seckillQuantity = ref(1);
const activeTab = ref("specs");

// Zoom functionality
const isHovering = ref(false);
const mouseX = ref(0);
const mouseY = ref(0);
const originalImage = ref<HTMLImageElement | null>(null);

const canAddToCart = computed(() => {
  const stock = product.value?.storNum;
  const hasStock = stock ? parseFloat(stock) > 0 : false;
  const isValidQty = isValidQuantity.value;
  return hasStock && isValidQty;
});

// 是否可以秒杀
const canSeckill = computed(() => {
  if (seckillPromotions.value.length === 0) return false;
  const seckill = seckillPromotions.value[0];
  return Math.floor(Number(seckill.seckillStorNum)) > 0;
});

// 获取最小数量
const minQuantity = computed(() => {
  if (!product.value) return 1;
  // 如果是中包装且不支持拆零，最小数量为midpack
  if (product.value.midpack > 1 && product.value.isMidpackSaleDisabled === 1) {
    return product.value.midpack;
  }
  return 1;
});

// 获取数量步长
const quantityStep = computed(() => {
  if (!product.value) return 1;
  // 如果是中包装且不支持拆零，步长为midpack
  if (product.value.midpack > 1 && product.value.isMidpackSaleDisabled === 1) {
    return product.value.midpack;
  }
  return 1;
});

// 验证数量是否有效
const isValidQuantity = computed(() => {
  if (!product.value) return true;
  // 如果是中包装且不支持拆零，数量必须是midpack的倍数
  if (product.value.midpack > 1 && product.value.isMidpackSaleDisabled === 1) {
    return selectedQuantity.value % product.value.midpack === 0;
  }
  return true;
});

// 自动调整数量为合适的倍数
function adjustQuantityToMultiple(inputQuantity: number) {
  if (!product.value) return inputQuantity;
  
  // 如果是中包装且不支持拆零
  if (product.value.midpack > 1 && product.value.isMidpackSaleDisabled === 1) {
    const midpack = product.value.midpack;
    const maxStock = Math.max(minQuantity.value, parseInt(product.value.storNum) || 10);
    
    // 计算向上和向下的倍数
    const lowerMultiple = Math.floor(inputQuantity / midpack) * midpack;
    const upperMultiple = Math.ceil(inputQuantity / midpack) * midpack;
    
    // 如果向上的倍数不超过库存，优先选择向上
    if (upperMultiple <= maxStock) {
      return upperMultiple;
    }
    // 否则选择向下的倍数，但不能小于最小数量
    else if (lowerMultiple >= minQuantity.value) {
      return lowerMultiple;
    }
    // 如果都不满足，返回最小数量
    else {
      return minQuantity.value;
    }
  }
  
  return inputQuantity;
}

// 监听数量变化，自动调整
watch(selectedQuantity, (newValue) => {
  if (!product.value) return;
  
  // 如果是中包装且不支持拆零
  if (product.value.midpack > 1 && product.value.isMidpackSaleDisabled === 1) {
    const adjustedValue = adjustQuantityToMultiple(newValue);
    
    // 如果调整后的值与当前值不同，需要更新
    if (adjustedValue !== newValue) {
      // 使用 nextTick 避免无限循环
      nextTick(() => {
        selectedQuantity.value = adjustedValue;
      });
    }
  }
});


async function toggleFavorite() {
  if (!product.value) return;
  await collectStore.toggleCollect(product.value.id);
  await checkCollectStatus(); // 操作完成后重新检查收藏状态
}

// Handle mouse move for zoom
function handleMouseMove(e: MouseEvent) {
  if (!originalImage.value) return;
  
  const rect = originalImage.value.getBoundingClientRect();
  const x = e.clientX - rect.left;
  const y = e.clientY - rect.top;
  
  // Clamp values to ensure they're within bounds
  const clampedX = Math.max(0, Math.min(rect.width, x));
  const clampedY = Math.max(0, Math.min(rect.height, y));
  
  // Update mouse position as percentage
  mouseX.value = (clampedX / rect.width) * 100;
  mouseY.value = (clampedY / rect.height) * 100;
}

// Lens style for hover indicator
const lensStyle = computed(() => {
  const lensSize = 30; // percentage of image size
  const x = Math.max(0, Math.min(100 - lensSize, mouseX.value - lensSize / 2));
  const y = Math.max(0, Math.min(100 - lensSize, mouseY.value - lensSize / 2));
  
  return {
    width: `${lensSize}%`,
    height: `${lensSize}%`,
    left: `${x}%`,
    top: `${y}%`,
  };
});

// Zoom preview style
const zoomStyle = computed(() => {
  if (!product.value?.mainPic) return {};
  
  const zoomFactor = 2.5;
  
  // Calculate background position in pixels
  // The zoom container is 500x500, original is 420x420
  const zoomContainerSize = 500;
  const bgSize = zoomContainerSize * zoomFactor; // 1250px
  
  // Map mouse position (0-100%) to pixels that should be centered in view
  // When mouse is at 0%, we want to show the top/left (position 0)
  // When mouse is at 100%, we want to show the bottom/right
  const mouseXPixel = (mouseX.value / 100) * zoomContainerSize;
  const mouseYPixel = (mouseY.value / 100) * zoomContainerSize;
  
  // Calculate how much to offset the background
  // We want the point under the mouse to be in the center of the zoom view
  const bgX = -(mouseXPixel * zoomFactor - zoomContainerSize / 2);
  const bgY = -(mouseYPixel * zoomFactor - zoomContainerSize / 2);
  
  // Clamp values to prevent showing outside the image
  const clampedBgX = Math.max(-(bgSize - zoomContainerSize), Math.min(0, bgX));
  const clampedBgY = Math.max(-(bgSize - zoomContainerSize), Math.min(0, bgY));
  
  return {
    backgroundImage: `url('${product.value.mainPic}')`,
    backgroundSize: `${bgSize}px ${bgSize}px`,
    backgroundPosition: `${clampedBgX}px ${clampedBgY}px`,
    backgroundRepeat: 'no-repeat',
    width: '100%',
    height: '100%',
  };
});


async function addToCart() {
  if (!canAddToCart.value) {
    ElMessage.warning("商品库存不足");
    return;
  }

  if (!product.value) return;

  // Prevent multiple clicks
  if (isAddingToCart.value) {
    return;
  }

  // 验证数量
  if (!isValidQuantity.value) {
    ElMessage.warning(
      `该商品不支持拆零，数量必须是${product.value.midpack}的倍数`
    );
    return;
  }

  // 如果是不可拆零的中包装商品，检查是否需要确认
  let shouldConfirm = false;
  let confirmMessage = "";
  
  if (product.value.midpack > 1 && product.value.isMidpackSaleDisabled === 1) {
    const currentQty = selectedQuantity.value;
    const midpack = product.value.midpack;
    const unit = product.value.unit;
    
    // 如果当前数量不等于用户可能期望的数量，需要确认
    if (currentQty % midpack === 0 && currentQty >= midpack) {
      shouldConfirm = true;
      confirmMessage = `该商品不支持拆零，将按 ${currentQty} ${unit}（${currentQty / midpack} 中包装）加入购物车，是否确认？`;
    }
  }

  // 显示确认对话框
  if (shouldConfirm) {
    try {
      await ElMessageBox.confirm(confirmMessage, "确认加入购物车", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "info",
      });
    } catch {
      return; // 用户取消
    }
  }

  // Set loading state
  isAddingToCart.value = true;

  try {
    const success = await cartStore.addItemToCart(
    product.value.goodsId,
    selectedQuantity.value
  );
  if (success) {
    const packingInfo =
      product.value.midpack > 1 && product.value.isMidpackSaleDisabled === 1
        ? `（按${product.value.midpack}${product.value.unit}计）`
        : "";

    ElMessage.success({
      message: `已将 ${selectedQuantity.value}【${product.value.title}】${packingInfo}加入购物车`,
      duration: 2000,
    });

    // 重置数量为最小有效数量
    selectedQuantity.value = minQuantity.value;
  } else {
    // ElMessage.error('加入购物车失败');
  }
  } finally {
    // Always reset loading state
    isAddingToCart.value = false;
  }
}

function handleShare() {
  const currentUrl = window.location.href;
  copy(currentUrl);
  ElMessage.success("链接已复制到剪贴板");
}

// 处理图片错误
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement;
  if (img) {
    img.src = "/images/no.jpg";
  }
};

// 格式化批次日期
function formatBatchDate(dateString: string): string {
  if (!dateString) return "";

  try {
    const date = new Date(dateString);
    if (isNaN(date.getTime())) return dateString;

    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");

    return `${year}-${month}-${day}`;
  } catch (error) {
    return dateString;
  }
}

// 判断近效期是否小于180天
function isNearExpiry(dateString: string | null): boolean {
  if (!dateString) return false;

  try {
    const expiryDate = new Date(dateString);
    const today = new Date();

    // 计算距离过期还有多少天
    const diffTime = expiryDate.getTime() - today.getTime();
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

    // 如果距离过期小于等于180天，则标记为近效期
    return diffDays <= 180 && diffDays >= 0;
  } catch (error) {
    return false;
  }
}

// 在新标签页打开商品详情
function openProductInNewTab(productId: number) {
  const url = `/product/${productId}`;
  window.open(url, '_blank');
}

// 秒杀购买状态
const isSeckillPurchasing = ref(false)

// 处理秒杀购买
async function handleSeckillPurchase() {
  if (!canSeckill.value || !product.value) return;
  
  if (isSeckillPurchasing.value) {
    return;
  }
  
  isSeckillPurchasing.value = true;
  
  const seckill = seckillPromotions.value[0];
  const quantity = seckillQuantity.value;
  
  // 检查数量是否超过限购
  if (quantity > Math.floor(Number(seckill.seckillNum))) {
    ElMessage.warning(`秒杀商品单次最多可购买${Math.floor(Number(seckill.seckillNum))}件`);
    return;
  }
  
  // 检查库存
  if (quantity > Math.floor(Number(seckill.seckillStorNum))) {
    ElMessage.warning(`秒杀商品库存不足，仅剩${Math.floor(Number(seckill.seckillStorNum))}件`);
    return;
  }
  
  try {
    // 获取秒杀活动的促销信息
    const seckillWithPromo = seckillPromotions.value[0] as any;
    const promotion = seckillWithPromo.promotion;
    
    if (!promotion) {
      ElMessage.error('找不到对应的秒杀活动');
      return;
    }
    
    // 确认对话框
    await ElMessageBox.confirm(
      `确认抢购 ${product.value.title} ${quantity}件吗？\n秒杀价：¥${Number(seckill.seckillPrice).toFixed(2)}\n总价：¥${(Number(seckill.seckillPrice) * quantity).toFixed(2)}`,
      '确认秒杀',
      {
        confirmButtonText: '确认抢购',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    const response = await promotionApi.createSeckillOrder({
      billNo: promotion.billNo,
      goodsId: product.value.goodsId,
      quantity: quantity,
      remark: '秒杀订单'
    });
    
    if (response.code === 1000) {
      ElMessage.success(`秒杀成功！订单号：${response.data.orderNum}`);
      router.push('/my-orders');
    } else {
      throw new Error(response.message || '秒杀失败');
    }
  } catch (error: any) {
    if (error === 'cancel') return;
    ElMessage.error(error.message || '秒杀失败，请重试');
  } finally {
    isSeckillPurchasing.value = false;
  }
}

// 买赠购买状态
const isBuyGiftPurchasing = ref(false)

// 处理买赠购买
async function handleBuyGiftPurchase() {
  if (!canAddToCart.value || !product.value) return;
  
  if (isBuyGiftPurchasing.value) {
    return;
  }
  
  isBuyGiftPurchasing.value = true;
  
  const buyGift = buyGiftPromotions.value[0];
  const quantity = Number(buyGift.num); // 买赠的数量是固定的
  
  try {
    // 获取买赠活动的促销信息
    const buyGiftWithPromo = buyGiftPromotions.value[0] as any;
    const promotion = buyGiftWithPromo.promotion;
    
    if (!promotion) {
      ElMessage.error('找不到对应的买赠活动');
      return;
    }
    
    const discountedPrice = calculateDiscountedPrice(Number(buyGift.taxprice));
    const totalPrice = discountedPrice * quantity;
    
    // 构建确认信息
    let confirmMessage = `确认购买 ${product.value.title} ${quantity}件吗？\n折后单价：¥${discountedPrice.toFixed(2)}\n总价：¥${totalPrice.toFixed(2)}`;
    
    // 添加赠品信息
    if (buyGift.freeGoodsInfo && buyGift.freeGoodsInfo.id) {
      confirmMessage += `\n赠送商品：${buyGift.freeGoodsInfo.title} ${Number(buyGift.freeNum)}件`;
    } else {
      confirmMessage += `\n赠送：${buyGift.remark || '赠品信息待更新'}`;
    }
    
    // 确认对话框
    await ElMessageBox.confirm(
      confirmMessage,
      '确认购买',
      {
        confirmButtonText: '确认购买',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    // 构建备注信息
    let remark = `买赠订单：购买 ${product.value.title}`;
    if (buyGift.freeGoodsInfo && buyGift.freeGoodsInfo.id) {
      remark += `，赠送 ${buyGift.freeGoodsInfo.title}`;
    } else {
      remark += `，${buyGift.remark || '赠品信息待更新'}`;
    }
    
    const response = await promotionApi.createBuyGiftOrder({
      billNo: promotion.billNo,
      goodsId: product.value.goodsId,
      quantity: quantity,
      remark: remark
    });
    
    if (response.code === 1000) {
      ElMessage.success(`买赠订单创建成功！订单号：${response.data.orderNum}`);
      router.push('/my-orders');
    } else {
      throw new Error(response.message || '创建订单失败');
    }
  } catch (error: any) {
    if (error === 'cancel') return;
    ElMessage.error(error.message || '创建订单失败，请重试');
  } finally {
    isBuyGiftPurchasing.value = false;
  }
}

// 查看套餐促销
function viewComboPromotions() {
  router.push('/promotions/combo');
}

// 计算用户折扣后的价格
function calculateDiscountedPrice(price: number): number {
  const discount = userStore.userInfo?.discount || 1;
  return Number((price * discount).toFixed(2));
}

</script>

<style scoped>
.product-gallery .thumbnail-list img.border-red-500 {
  border-width: 2px;
  padding: 1px;
}

.el-radio.is-bordered {
  margin-right: 8px;
  margin-bottom: 8px;
  border-radius: 4px;
}

.el-radio.is-bordered.el-radio--small {
  padding: 6px 10px 0 10px;
  height: 30px;
  line-height: 20px;
}

.el-radio__input {
  display: none;
}

/* Zoom functionality styles */
.main-image-container {
  cursor: crosshair;
}

.product-detail-tabs :deep(.el-tabs__header) {
  margin-bottom: 0;
  padding: 0 1rem;
  background-color: #f9fafb;
  border-bottom: 1px solid #e5e7eb;
}

.product-detail-tabs :deep(.el-tabs__nav-wrap::after) {
  height: 0px;
}

.product-detail-tabs :deep(.el-tabs__item) {
  padding: 0 16px;
  height: 50px;
  line-height: 50px;
  font-size: 1rem;
}

.product-detail-tabs :deep(.el-tabs__item.is-active) {
  color: #ef4444;
  font-weight: 600;
}

.product-detail-tabs :deep(.el-tabs__active-bar) {
  background-color: #ef4444;
  height: 3px;
}

/* Vue Magnifier 自定义样式 */
.vue-magnifier__magnifier {
  border-radius: 8px;
  overflow: hidden;
}

.vue-magnifier__magnifying-glass {
  border: 2px solid #666 !important;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15) !important;
}

/* 响应式设计 - 在小屏幕上隐藏放大镜 */
@media (max-width: 1024px) {
  .vue-magnifier__magnifying-glass {
    display: none !important;
  }
}

.product-item:hover p {
  color: #ef4444;
}

/* Promotion styles */
.promotion-details {
  animation: fadeIn 0.5s ease-in;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.promotion-details .el-tag {
  font-weight: 600;
}
</style>
